/*
 * @(#)PageController.java
 * PageController类作为SpringMVC的Controller层
 * 主要负责对页面方面的请求的映射处理，调用Service层的方法对请求进行处理并返回结果
 * Copyright 2015 上海领智信息科技有限公司, Inc. All rights reserved.
 * @author reeves
 * @Time 2015/04/20 21:37:00
 * @version 1.0
 */

package com.version1_1.controller;

import com.util.aliyun.OCSutils;
import com.util.format.MapToJson;
import com.util.property.Properties;
import com.version1_1.service.PageService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;


@Controller
public class PageController {
    /*创建log4j对象*/
    private static final Logger LOGGER = Logger.getLogger(PageController.class);

    @Autowired
    private PageService pageService;


    /**
     * 调用接口：http://localhost:8080/kuibuversion1/page/getPageInfo/{pageId}
     *
     * @Description: 根据pageId, 得到指定页面的信息数据
     * @warnning: 依赖于单例pageModel，pageModel基于磁盘上的文件，并且项目启动运行期间pageModel载入内存不能动态改变
     * @warnning: 此接口在service层使用了cache缓存，缓存时间 10分钟
     */
    @RequestMapping(value = "/page/getPageInfo/{pageId}", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String getPageInfo(HttpServletRequest request, @PathVariable("pageId") int pageId) {
        pageService.doRead(pageId); // 记录文章被阅读

        boolean cleanCache = false;
        if (request.getParameter("cleanCache") != null) {
            cleanCache = Boolean.parseBoolean((String) request.getParameter("cleanCache"));
        }
        OCSutils ocSutils = new OCSutils();
        if (ocSutils.get("pageInfo" + pageId) == null) {
            ocSutils.save("pageInfo" + pageId, pageService.getPageInfo(pageId, cleanCache), 600);
            return pageService.getPageInfo(pageId, cleanCache);
        } else {
            return (String) ocSutils.get("pageInfo" + pageId);
        }
    }

    /**
     * 调用接口：http://localhost:8080/kuibuversion1/page/getPageOtherInfo/{userId}/{pageId}
     *
     * @param pageId
     * @Description: 获取除正文之外的其他信息
     */
    @RequestMapping(value = "/page/getPageOtherInfo/{userId}/{pageId}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String getPageOtherInfo(@PathVariable("pageId") int pageId, @PathVariable("userId") int userId) {

        return pageService.getPageOtherInfo(userId, pageId);
    }

    /**
     * 调用接口：http://localhost:8080/kuibuversion1/page/newMainPage/{itemNumber}/{userId}/{pageNumber}/{cacheTag}
     *
     * @Description: 登陆用户根据分页数得到主页面的预览信息，新接口
     * @description: 图片传递url
     */
    @RequestMapping(value = "/page/newMainPage/{itemNumber}/{userId}/{pageNumber}/{cacheTag}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String getNewMainPage(@PathVariable("userId") int userId,
                                 @PathVariable("itemNumber") int firstType,
                                 @PathVariable("pageNumber") int pageNumber,
                                 @PathVariable("cacheTag") boolean cacheTag) {

        return pageService.getNewMainPage(userId, firstType,
                pageNumber, Properties.Size_MainPageThird, cacheTag);
    }

    /**
     * 调用接口：http://localhost:8080/kuibuversion1/page/mainPage/{itemNumber}/{userId}/{pageNumber}
     *
     * @Description: 登陆用户根据分页数得到主页面的预览信息，原接口
     * @description: 图片传递url
     */
    @RequestMapping(value = "/page/mainPage/{itemNumber}/{userId}/{pageNumber}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String getMainPage(@PathVariable("userId") int userId,
                              @PathVariable("itemNumber") int firstType,
                              @PathVariable("pageNumber") int pageNumber)
            throws UnsupportedEncodingException {

        return pageService.getMainPage(userId, firstType,
                pageNumber, Properties.Size_MainPageThird);
    }


    /**
     * 调用接口：http://localhost:8080/kuibuversion1/page/mainPageNoLogin/{pageNumber}
     *
     * @Description: 未登陆用户根据分页数得到主页面的预览信息
     * @description: 图片传递url
     */
    @RequestMapping(value = "/page/mainPageNoLogin/{pageNumber}", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String getMainPageNoLogin(HttpServletRequest request,
                                     @PathVariable("pageNumber") int pageNumber)
            throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        String mainFocusList = request.getParameter("mainFocusList");

        if (mainFocusList == null) {
            LOGGER.error("未登录用户主页面信息获取错误,请求mainFocusList为null!");
            return "{\"isLast\":true}";
        }

        return pageService.getMainPageNoLogin(mainFocusList, pageNumber, Properties.Size_MainPageThird);
    }


    /**
     * 调用接口：http://localhost:8080/kuibuversion1/page/newMainPageNoLogin/{pageNumber}/{cacheTag}
     *
     * @Description: 未登陆用户根据分页数得到主页面的预览信息，新接口
     * @description: 图片传递url
     */
    @RequestMapping(value = "/page/newMainPageNoLogin/{pageNumber}/{cacheTag}", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String getNewMainPageNoLogin(HttpServletRequest request,
                                        @PathVariable("pageNumber") int pageNumber, @PathVariable("cacheTag") boolean cacheTag)
            throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        String mainFocusList = request.getParameter("mainFocusList");

        if (mainFocusList == null) {
            LOGGER.error("未登录用户主页面信息获取错误,请求mainFocusList为null!");
            return "{\"isLast\":true}";
        }

        return pageService.getNewMainPageNoLogin(mainFocusList, pageNumber, Properties.Size_MainPageThird, cacheTag);
    }


    /**
     * 调用接口：http://localhost:8080/kuibuversion1/page/thirdPage/{secondType}/{thirdTypeName}/{pageNumber}
     *
     * @Description: 根据分页数得到三级分类页面的预览信息
     * @description: 图片传递url
     */
    @RequestMapping(value = "/page/thirdPage/{secondType}/{thirdTypeName}/{pageNumber}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String getThirdPage(@PathVariable("secondType") int secondType,
                               @PathVariable("pageNumber") int pageNumber,
                               @PathVariable("thirdTypeName") String thirdTypeName)
            throws UnsupportedEncodingException {

        return pageService.getThirdPage(secondType,
                thirdTypeName, pageNumber, Properties.PageSize_ThirdPage);
    }

    /**
     * 调用接口：http://localhost:8080/kuibuversion1/page/secondPage/{pageNumber}
     *
     * @Description: 根据分页数得到二级分类界面的预览信息
     * @description: 图片传递url
     */
    @RequestMapping(value = "/page/secondPage/{pageNumber}", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String getSecondPage(HttpServletRequest request,
                                @PathVariable("pageNumber") int pageNumber)
            throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        String secondFocusListString = (String) request.getParameter("secondFocusListString");

        if (secondFocusListString == null) {
            LOGGER.error("获取二级分类界面的预览信息错误,secondFocusListString为null!");
            return "{\"result\":[]}";
        }

        return pageService.getSecondPage(
                secondFocusListString, pageNumber, Properties.PageSize_SecondPage);
    }

    /**
     * 调用接口：http://localhost:8080/kuibuversion1/page/comPraise
     *
     * @Description: 改变评论的点赞数
     */
    @RequestMapping(value = "/page/comPraise", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String pageComPraise(HttpServletRequest request)
            throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");

        /**
         * commentString:
         * 取消点赞：{"commentType":-1,"commentId":}
         * 点赞：{"commentType":1,"commentId":,"senderId":,"receiverId":,"date":""}
         */
        String commentString = (String) request.getParameter("commentString");
        if (commentString == null) {
            return "{\"commentOK\":false}";
        }

        return pageService.setPageComPraise(commentString);
    }

    /**
     * 调用接口：http://localhost:8080/kuibuversion1/page/addComment
     *
     * @Descrition: 新增一条评论或回复
     */
    @RequestMapping(value = "/page/addComment", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String pageComment(HttpServletRequest request) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");

        /**
         * commentString:
         * 新增评论或回复：{"pageId":10000,"senderId":37,"toComId":-1,"date":"2015-11-14","comment":"fwfwf"}
         *
         */
        //String commentString = jsonObject.get("commentString").toString();
        String commentString = (String) request.getParameter("commentString");
        if (commentString == null) {
            LOGGER.error("新增一条评论错误,未接收到客户端参数!");
            return "{\"commentOK\":false}";
        }

        return pageService.setPageComment(commentString);
    }


    /**
     * 调用接口：http://localhost:8080/kuibuversion1/page/getCommentList/{userId}/{pageId}/{pageNumber}
     *
     * @Description: 获取文章评论列表数据
     */
    @RequestMapping(value = "/page/getCommentList/{userId}/{pageId}/{pageNumber}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String getCommentList(@PathVariable("userId") int userId,
                                 @PathVariable("pageId") int pageId,
                                 @PathVariable("pageNumber") int pageNumber)
            throws UnsupportedEncodingException {

        return pageService.getCommentListString(userId, pageId,
                pageNumber, Properties.PageSize_PageComment);
    }

    /**
     * 调用接口：http://localhost:8080/kuibuversion1/page/read/{pageId}
     *
     * @Description: 记录文章被用户阅读
     */
    @RequestMapping(value = "/page/read/{pageId}", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String doRead(@PathVariable("pageId") int pageId) {

        return pageService.doRead(pageId);
    }


    /**
     * 调用接口：http://localhost:8080/kuibuversion1/page/search/{key}
     *
     * @Description: 搜索文章标题
     */
    @RequestMapping(value = "/page/search/{key}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String searchPage(@PathVariable("key") String key) throws UnsupportedEncodingException {
        return pageService.searchPage(key);
    }

    /**
     * 调用接口：http://localhost:8080/kuibuversion1/page/transmit/{pageId}
     *
     * @Description: 记录一次文章被转发(分享)
     */
    @RequestMapping(value = "/page/transmit/{pageId}", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String doTransmitCount(@PathVariable("pageId") int pageId) {
        /**
         * 记录文章被转发(分享)
         */
        return pageService.doTransmitCount(pageId);
    }

    /**
     * 调用接口：http://localhost:8080/kuibuversion1/page/pageContentComment/{userId}/{pageId}/{commentType}
     *
     * @Description: 对文章内容进行评论好文和水文
     */
    @RequestMapping(value = "/page/pageContentComment/{userId}/{pageId}/{commentType}", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String pageContentComment(@PathVariable("userId") int userId, @PathVariable("pageId") int pageId, @PathVariable("commentType") int commentType) {

        return new MapToJson("pageContentCommentResult", pageService.pageContentComment(userId, pageId, commentType)).toJsonString();
    }

    /**
     * 调用接口：http://localhost:8080/kuibuversion1/page/postComInPage
     *
     * @Description: 在文章中对三级分类信息进行评论和提供信息源
     */
    @RequestMapping(value = "/page/postComInPage", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String postComInPage(HttpServletRequest request) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        boolean result = false;

        /**
         * comInPageStr:{"userId":,"wantedInfo":"","infoSource":""}
         */
        String comInPageStr = request.getParameter("comInPageStr");

        // 若没有接收到客户端发送的参数
        if (comInPageStr == null) {
            LOGGER.error("在文章中对三级分类信息进行评论和提供信息源出错,无法获得客户端发送参数: comInPageStr");
        } else {
            result = pageService.postComInPage(comInPageStr);
        }
        return new MapToJson("postComInPageResult", result).toJsonString();
    }


    /**
     * 获取评论回复信息列表
     * 调用接口：http://localhost:8080/kuibuversion1/page/comReply/{commentId}
     *
     * @param commentId
     * @return
     */
    @RequestMapping(value = "/page/comReply/{commentId}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String getCommentReply(@PathVariable("commentId") int commentId) throws UnsupportedEncodingException {

        /**
         * 返回信息：comReplyStr
         * 格式：[{"replyerName":"","replyerPhoto":"","replyDate":"","replyContent":""}...]
         */
        return pageService.getCommentReply(commentId);
    }


}
